<template>
  <div class="dc-list card">
    <div class="title">
      <slot name="title">数据</slot>
    </div>
    <div class="content">
      <sa-draggable
        v-model="listData"
        item-key="element"
        :animation="300"
        handle=".sortable-drag"
        @end="updateItem"
      >
        <template #item="{ element, index }">
          <div class="list-item">
            <div class="list-item-posi sa-flex">
              <sa-icon class="sortable-drag" icon="sa-round" />
              <slot name="deleteIcon">
                <span class="list-delete" @click="deleteItem(index)">删除</span>
              </slot>
            </div>
            <slot name="listItem" :element="element" :index="index"></slot>
          </div>
        </template>
      </sa-draggable>
      <slot name="add" v-if="listData?.length != leng">
        <el-button class="add-button" icon="Plus" @click="addItem">添加</el-button>
      </slot>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'dc-list',
  };
</script>
<script setup>
  import { ref, watch } from 'vue';
  import SaDraggable from 'vuedraggable';
  import { cloneDeep } from 'lodash';

  const emit = defineEmits(['update:modelValue']);
  const props = defineProps(['modelValue', 'itemProp', 'leng']);

  const listData = ref(props.modelValue || []);
  watch(
    () => props.modelValue,
    () => {
      listData.value = props.modelValue;
    },
  );

  function addItem() {
    listData.value.push(cloneDeep(props.itemProp));
  }
  function deleteItem(index) {
    listData.value.splice(index, 1);
  }
  function updateItem() {
    emit('update:modelValue', listData.value);
  }
</script>
<style lang="scss" scoped>
  .dc-list {
    .title {
      margin-bottom: 0;
    }
    .list-item {
      padding: 8px 0;
      border-bottom: 1px solid var(--sa-space);
      background: var(--sa-background-assist);
      &:last-of-type {
        border-bottom: none;
        // margin-bottom: 16px;
      }
      &:hover {
        background: var(--t-bg-hover);
        :deep() {
          .list-item-posi {
            & > * {
              display: block;
            }
          }
        }
      }
      :deep() {
        .list-item-posi {
          padding: 0 4px 16px;
          height: 32px;
          & > * {
            display: none;
          }

          .sortable-drag {
            font-size: 16px;
            margin-right: 8px;
            cursor: pointer;
          }

          .list-delete {
            color: #ff4d4f;
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
